<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>getUserMediaAPI 示例</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      button {
        width: 100px;
        height: 30px;
        font-size: 18px;
        margin: 20px;
      }
    </style>
  </head>
  <body>
    <button id="btn1">开启摄像头</button>
    <button id="btn2">关闭摄像头</button>
    <video id="video" controls width="100%" height="300px"></video>
    <script>
      // 获取 DOM 元素
      var btn1 = document.getElementById("btn1");
      var btn2 = document.getElementById("btn2");
      var video = document.getElementById("video");
      var constraints = {
        audio: true,
        video: true,
      };

      // 开启摄像头
      btn1.onclick = function () {
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            video.srcObject = stream;
            video.play();

            // 关闭摄像头
            btn2.onclick = function () {
              stream.getTracks().forEach(function (track) {
                track.stop();
              });
            };
          })
          .catch(function (err) {
            console.log("getUserMedia() error: " + err);
          });
      };
    </script>
  </body>
</html>

